package cn.south.campus.admin.campus.service.impl;

import cn.south.campus.admin.campus.mapper.WithdrawalAuditMapper;
import cn.south.campus.admin.campus.model.entity.WithdrawalAudit;
import cn.south.campus.admin.campus.model.req.AuditReq;
import cn.south.campus.admin.campus.model.req.WithdrawalAuditReq;
import cn.south.campus.admin.campus.model.vo.WithdrawalAuditVo;
import cn.south.campus.admin.campus.service.WithdrawalAuditService;
import cn.south.campus.common.exceptions.BusinessException;
import cn.south.campus.common.model.enums.CommonEnums;
import cn.south.campus.common.utils.HttpUtils;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *
 * </p>
 *
 * @author chow
 * @since 2024/11/14 15:11
 */
@Service
public class WithdrawalAuditServiceImpl extends ServiceImpl<WithdrawalAuditMapper, WithdrawalAudit> implements WithdrawalAuditService {

    @Value("${campus.url}")
    private String businessUrl;

    @Resource
    private WithdrawalAuditMapper withdrawalAuditMapper;

    @Override
    public IPage<WithdrawalAuditVo> pageQuery(WithdrawalAuditReq req) {
        IPage<WithdrawalAudit> auditVoIPage = withdrawalAuditMapper.pageQuery(req.getPageDto(), req);
        return auditVoIPage.convert(WithdrawalAuditVo::convert);
    }

    @Override
    public void audit(AuditReq req) {
        Map<String, Object> httpReq = new HashMap<>();
        WithdrawalAudit withdrawalAudit = withdrawalAuditMapper.selectById(req.getId());
        httpReq.put("id", withdrawalAudit.getId());
        httpReq.put("bizNo", withdrawalAudit.getBizNo());
        httpReq.put("status", req.getStatus());
        httpReq.put("userId", withdrawalAudit.getUserId());
        httpReq.put("amount", withdrawalAudit.getAmount().toString());
        String putReq = HttpUtils.putReq(httpReq, businessUrl + "wallet/withdraw/callback");
        JSONObject jsonObject = JSON.parseObject(putReq);
        if (jsonObject == null || !jsonObject.getString("code").equals("0")) {
            throw new BusinessException(CommonEnums.SYSTEM_ERROR);
        }
        withdrawalAudit.setStatus(req.getStatus());
        withdrawalAuditMapper.updateById(withdrawalAudit);
    }
}
